﻿using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MebAppLib
{
    /// <summary>
    /// 使用using语法或显式调用Dispose，Mutex创建者可以释放该Mutex所保护的内存映射文件和Mutex本身
    /// </summary>
    public class SharedMemoryMutexHandle : IDisposable
    {
        public string Id { get; private set; }
        internal SharedMemoryMutexHandle(string id)
        {
            this.Id = id;
        }

        public void Dispose()
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(Id, 1024000))
            {
                using (var mutex = SharedMemroy.OpenMutex(Id + "mutex", true))
                {
                    mutex.WaitOne();
                    mutex.Dispose();
                }
            }
        }
    }
}
